package com.zretc.service.impl;

import com.zretc.config.FastDFSUtils;
import com.zretc.dao.PermissionMapper;
import com.zretc.dao.RoleMapper;
import com.zretc.dao.UserInfoMapper;
import com.zretc.entity.Permission;
import com.zretc.entity.ResponseResult;
import com.zretc.entity.Role;
import com.zretc.entity.UserInfo;
import com.zretc.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

/**
 * @author 周文涛
 * 2020年8月19日20:27:34
 * 用户业务层
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;


    // 登录时用户判断
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据账号获取用户
        UserInfo userByName = userInfoMapper.findUserByName(username);
        if (userByName == null){
            throw new UsernameNotFoundException("用户名不存在!");
        }
        // 根据用户编号获取角色
        List<Role> roles = roleMapper.findAllByUser(userByName.getUserId());
        userByName.setRoles(roles);

        return userByName;
    }


    @Override
    public List<Permission> getUserMenu() {
        // 获取登录用户
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        UserDetails userDetails = this.loadUserByUsername(name);
        UserInfo userInfo = (UserInfo)userDetails;
        return permissionMapper.findAllByUser(userInfo.getUserId());
    }

    @Override
    public List<Permission> getAll() {
        return permissionMapper.findAll();
    }

    @Override
    public List<Permission> getAllPermission() {
        return permissionMapper.findAllPermission();
    }

    @Override
    public int register(UserInfo userInfo) {
        //如果用户名存在，返回错误
        if (userInfoMapper.findUserByName(userInfo.getUsername()) != null) {
            return -1;
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(userInfo.getPassword());
        userInfo.setUserPassword(encode);
        return userInfoMapper.insert(userInfo);
    }

    @Override
    public List<UserInfo> getAllUser(Map<String, String> condition) {
        // 获取关键字
        String keyword = condition.get("keyword");
        if(keyword == null || "".equals(keyword)){
            condition.put("keyword",null);
        }else{
            condition.put("keyword","%"+keyword+"%");
        }
        List<UserInfo> all = userInfoMapper.findAll(condition);
        return all;
    }

    @Override
    public ResponseResult updateEnabled(UserInfo userInfo) {
        int i = userInfoMapper.updateEnabled(userInfo.isEnabled(),userInfo.getUserId());
        if(i==1 && userInfo.isEnabled()){
            return ResponseResult.ok("已启用");
        }else if(i==1 && !userInfo.isEnabled()){
            return ResponseResult.ok("已禁用");
        }else{
            return ResponseResult.error("更新失败");
        }
    }

    @Override
    public ResponseResult deleteUser(Integer userId) {
        if(userInfoMapper.delete(userId)==1){
            return ResponseResult.ok("删除成功");
        }
        return ResponseResult.error("删除失败");
    }

    @Override
    public UserDetails getLoginUser() {
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        UserDetails userDetails = this.loadUserByUsername(name);
        UserInfo userInfo = (UserInfo)userDetails;
        userInfo.setUserPassword(null);
        return userInfo;
    }

    @Override
    public ResponseResult updatePassword(Map<String,Object> map) {
        // 获取原密码
        String oldPassword = (String)map.get("oldpass");
        // 获取密码
        String password = (String)map.get("pass");
        // 获取登录用户
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        UserDetails userDetails = this.loadUserByUsername(name);
        UserInfo userInfo = (UserInfo)userDetails;
        // 先进行密码对比
        if(passwordEncoder.matches(oldPassword,userDetails.getPassword())){
            UserInfo user = new UserInfo();
            user.setUserId(userInfo.getUserId());
            // 密码加密
            user.setUserPassword(passwordEncoder.encode(password));
            // 更新密码
            if(userInfoMapper.update(user)==1){
                return ResponseResult.ok("修改成功");
            }else{
                return ResponseResult.error("修改失败");
            }
        }else{
            return ResponseResult.error("原密码错误");
        }

    }

    @Override
    public ResponseResult updateUserInfo(Map<String,Object> map) {
        UserInfo userInfo = new UserInfo();
        userInfo.setPhone((String)map.get("phone"));
        userInfo.setAddress((String)map.get("address"));
        userInfo.setTelephone((String)map.get("telephone"));
        userInfo.setName((String)map.get("name"));
        userInfo.setUserId((Integer) map.get("userId"));

        if(userInfoMapper.update(userInfo)==1){
            return ResponseResult.ok("修改成功");
        }else{
            return ResponseResult.error("修改失败");
        }
    }

    @Override
    @Transactional
    public ResponseResult updateUserFace(MultipartFile file, Integer userId) {
        try{
            if(file == null)
                throw new RuntimeException("文件为空");
            if(file.getSize() > 1024*1024)
                throw new RuntimeException("文件过大");
            if(!(file.getOriginalFilename().endsWith(".jpg")||file.getOriginalFilename().endsWith(".jpeg")||file.getOriginalFilename().endsWith(".png"))){
                throw new RuntimeException("文件类型错误");
            }
            // 获取用户原图片
            String oddImageAddress = userInfoMapper.selectUserImage(userId);

            String imageName = FastDFSUtils.upload(file);
            if(imageName == null){
                throw new RuntimeException("上传失败");
            }
            imageName = FastDFSUtils.IMG_ADDRESS+imageName;
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(userId);
            userInfo.setUserFace(imageName);

            if(userInfoMapper.update(userInfo) == 1){
                FastDFSUtils.deleteFile(oddImageAddress);
                return ResponseResult.ok("修改成功");
            }else {
                return ResponseResult.error("修改失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error(e.getMessage());
        }
    }


}
